package com.lza.framework.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lza.entity.User;
import com.lza.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;
    @Autowired
    private RestFulAccessDeniedHandler restFulAccessDeniedHandler;
    @Autowired
    private UserService userService;
    @Override
    @Bean
    public UserDetailsService userDetailsService(){
        return username->{
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("username", username);
            User admin = userService.getOne(queryWrapper);
            if(null!=admin){
                //System.out.println("这波在security的配置文件"+admin);
                return  admin;
            }
            return  null;
        };
    }

    /*
    走自己的登陆逻辑
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }


    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return  new JwtAuthenticationTokenFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()//使用jwt，不需要csrf
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)//基于token，不需要session
                .and()
                .authorizeRequests()
                .antMatchers("/user/login")
                .permitAll()//除了login其他都需要拦截
                .anyRequest()
                .authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationTokenFilter(),UsernamePasswordAuthenticationFilter.class)//添加jwt 登录授权过滤器
                //禁用缓存
                .headers()
                .cacheControl();
        //添加jwt 登录授权过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和没登录返回结果
        http.exceptionHandling()
                .accessDeniedHandler(restFulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }
}
